package com.study.talk.adapter;

// 导入所需的Android类和包

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.PopupMenu;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.databinding.ActivityMomentListBinding;
import com.study.talk.databinding.CommentBottomViewBinding;
import com.study.talk.databinding.MomentListViewItemBinding;
import com.study.talk.entity.MomentLike;
import com.study.talk.entity.resp.MomentResponse;
import com.study.talk.entity.vo.UpdateLikeStateVo;
import com.study.talk.net.NetApi;
import com.study.talk.net.OkHttp;
import com.study.talk.util.TimeAgoUtils;
import com.study.talk.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.netty.util.internal.StringUtil;

/** 定义MomentListAdapter类，继承自BaseAdapter，用于显示动态列表 */
public class MomentListAdapter extends RecyclerView.Adapter<MomentListAdapter.MomentItemViewHolder> {

    private CommentBottomViewBinding commentViewBinding;

    public final int FOOTER_VIEW_TYPE = 999;



    // 定义列表数据和活动上下文
    List<MomentResponse> data;
    BaseActivity activity;
    private Integer momentId;
    private BottomSheetDialog bottomSheetDialog;
    private ActivityMomentListBinding activityMomentListBinding;

    /** 构造函数，初始化数据和活动上下文 */
    @SuppressLint("InflateParams")
    public MomentListAdapter(List<MomentResponse> data, BaseActivity activity, ActivityMomentListBinding activityMomentListBinding) {
        this.data = data;
        this.activity = activity;
        this.activityMomentListBinding = activityMomentListBinding;
        //底部评论组件初始化一次就好了
        initCommentView(activity);
    }


    @Override
    public int getItemViewType(int position) {
        return position == data.size() ? FOOTER_VIEW_TYPE : 0;
    }

    @NonNull
    @Override
    public MomentItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == FOOTER_VIEW_TYPE) {  //footerView
            return new MomentItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.moment_list_view_item_footer_view, parent,false));
        }
        MomentListViewItemBinding momentListViewItemBinding = MomentListViewItemBinding.inflate(activity.getLayoutInflater(), parent, false);
        return new MomentItemViewHolder(momentListViewItemBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MomentItemViewHolder holder, int position) {

        //MMP谁能告诉我为什么RecycleView加个HeaderView，FooterView什么的怎么这么麻烦
        if (getItemViewType(position) == FOOTER_VIEW_TYPE) return;

        // 获取当前位置的动态对象
        MomentResponse moment = data.get(position);
        // 使用Glide加载头像图片

        MomentListViewItemBinding viewItemBinding = holder.momentListViewItemBinding;

        Glide.with(activity).load(OkHttp.URL + moment.getAvatar()).into(viewItemBinding.momentListViewItemHeadImg);

        // 设置用户名和动态内容
        viewItemBinding.momentListViewItemUsername.setText(moment.getUserName());
        viewItemBinding.momentListViewItemContent.setText(moment.getContent());

        initPhotoView(moment, viewItemBinding);
        // 初始化点赞视图
        initLikeView(moment, viewItemBinding);
        // 初始化时间视图
        initTimeView(moment, viewItemBinding);

        // 初始化评论视图
        initCommentView(moment, viewItemBinding);

        // 设置动态操作按钮的点击事件
        viewItemBinding.momentListViewItemAction.setOnClickListener(v -> {
            // 初始化菜单操作
            initMenuAction(moment, activity, v);
        });

    }

    // 获取指定位置的列表项的ID
    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return data.size() + 1;
    }

    /** 初始化评论视图 */
    private void initCommentView(BaseActivity activity) {

        // 设置发送评论按钮的点击事件
        activityMomentListBinding.momentListCommentMsgSendBt.setOnClickListener(v -> {
            // 检查输入内容是否为空
            if (activity.checkInput(activityMomentListBinding.momentListCommentMsgEdit, "请输入评论"))
                return;
            // 获取输入的评论内容
            String commentContent = activity.editTrim(activityMomentListBinding.momentListCommentMsgEdit);
            // 清空输入框
            activity.setText(activityMomentListBinding.momentListCommentMsgEdit, "");
            // 添加评论
            NetApi.addMomentComment(activity.getApp().user, momentId, commentContent, b -> {
                if (b) {
                    // 获取好友动态列表并更新数据
                    NetApi.getFriendMomentList(activity.getApp().user.getId(), data -> {
                        this.data = data;
                        activity.runOnUiThread(this::notifyDataSetChanged);
                    }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                    // 隐藏键盘
                    activity.hideKeyboard(v);
                } else {
                    // 显示评论失败的提示
                    ToastUtil.showToast(activity, "评论失败");
                }
            }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
        });
    }

    /** 初始化菜单操作 */
    @SuppressLint({"NonConstantResourceId", "NewApi"})
    private void initMenuAction(@NonNull MomentResponse moment, BaseActivity activity, View v) {
        // 设置动态ID
        momentId = moment.getId();
        // 创建弹出菜单
        PopupMenu popupMenu = new PopupMenu(activity, v);
        popupMenu.getMenuInflater().inflate(R.menu.moment_action_menu, popupMenu.getMenu());
        // 根据点赞状态设置菜单标题
        if (moment.getMyLikeState() == 1) popupMenu.getMenu().getItem(0).setTitle("取消点赞");
        popupMenu.show();
        // 设置菜单项的点击事件
        popupMenu.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.moment_action_like -> {
                    // 根据当前点赞状态更新点赞
                    if (moment.getMyLikeState() == 1) {
                        NetApi.updateMomentLike(new UpdateLikeStateVo(moment.getId(), activity.getApp().userId(), 0), b -> {
                            moment.setMyLikeState(0);
                            // 获取点赞列表并更新数据
                            NetApi.getLikeList(moment.getId(), data -> {
                                moment.setMomentLikes((ArrayList<MomentLike>) data);
                                activity.runOnUiThread(this::notifyDataSetChanged);
                            }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                        }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                    } else {
                        NetApi.addMomentLike(activity.getApp().user, moment.getId(), 1, b -> {
                            moment.setMyLikeState(1);
                            // 获取点赞列表并更新数据
                            NetApi.getLikeList(moment.getId(), data -> {
                                moment.setMomentLikes((ArrayList<MomentLike>) data);
                                activity.runOnUiThread(this::notifyDataSetChanged);
                            }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                        }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                    }
                }
                case R.id.moment_action_comment -> {
                    // 显示底部评论对话框
                    /**
                    if (bottomSheetDialog == null){
                        bottomSheetDialog = new BottomSheetDialog(activity);
                        bottomSheetDialog.setContentView(commentViewBinding.getRoot());
                    }
                    bottomSheetDialog.show();
                     */
                    activityMomentListBinding.momentListCommentLinearLayout.setVisibility(View.VISIBLE);
                }
            }
            return true;
        });
    }

    /** 初始化评论视图 */
    private void initCommentView(@NonNull MomentResponse moment, MomentListViewItemBinding viewItemBinding) {
        // 检查是否有评论，如果没有则隐藏评论列表
        if (moment.getMomentComments() == null && moment.getMomentComments().isEmpty()) {
            viewItemBinding.momentListViewItemCommentListView.setVisibility(View.GONE);
        } else {
            // 设置评论列表的适配器
            MomentCommentListAdapter momentCommentListAdapter = new MomentCommentListAdapter(moment.getMomentComments(), activity);
            viewItemBinding.momentListViewItemCommentListView.setLayoutManager(new LinearLayoutManager(activity));
            viewItemBinding.momentListViewItemCommentListView.setAdapter(momentCommentListAdapter);

        }
    }

    /** 初始化时间视图 */
    private void initTimeView(@NonNull MomentResponse moment, MomentListViewItemBinding viewItemBinding) {
        // 设置动态的创建时间
        viewItemBinding.momentListViewItemTime.setText(TimeAgoUtils.format(moment.getCreateTime()));
    }

    /** 初始化图片视图 */
    private void initPhotoView(@NonNull MomentResponse moment, MomentListViewItemBinding viewItemBinding) {
        // 检查是否有图片，如果没有则隐藏图片网格
        if (moment.getPhotos() == null && moment.getPhotos().isEmpty()) {
            viewItemBinding.momentListViewItemGridview.setVisibility(View.GONE);
        } else {
            // 根据图片数量设置网格列数
            GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, 3);
            switch (moment.getPhotos().size()) {
                case 1 -> gridLayoutManager.setSpanCount(1);
                case 2, 3, 4 -> gridLayoutManager.setSpanCount(2);
                case 5, 6, 7, 8, 9 -> gridLayoutManager.setSpanCount(3);
            }

            viewItemBinding.momentListViewItemGridview.setLayoutManager(gridLayoutManager);

            // 设置图片网格的适配器
            viewItemBinding.momentListViewItemGridview.setAdapter(new MomentListGridViewAdapter(moment.getPhotos(), activity));
        }
    }

    /** 初始化点赞视图 */
    private void initLikeView(@NonNull MomentResponse moment, MomentListViewItemBinding viewItemBinding) {
        // 检查是否有点赞，如果没有则隐藏点赞布局
        if (moment.getMomentLikes() == null || moment.getMomentLikes().isEmpty()) {
            viewItemBinding.momentListViewItemLikeLayout.setVisibility(View.GONE);
        } else {
            // 构建点赞用户名称字符串
            StringBuilder sb = new StringBuilder();
            for (MomentLike momentLike : moment.getMomentLikes()) {
                if (momentLike.getLikeState() == 1) {
                    sb.append(momentLike.getUserName());
                }
            }
            // 如果没有点赞用户则隐藏点赞布局
            if (StringUtil.isNullOrEmpty(sb.toString())) {
                viewItemBinding.momentListViewItemLikeLayout.setVisibility(View.GONE);
            } else {
                // 显示点赞布局并设置点赞用户名称
                viewItemBinding.momentListViewItemLikeLayout.setVisibility(View.VISIBLE);
                viewItemBinding.momentListViewItemLikeText.setText(sb.toString());
            }
        }
    }

    public static class MomentItemViewHolder extends ViewHolder {

        MomentListViewItemBinding momentListViewItemBinding;

        public MomentItemViewHolder(@NonNull MomentListViewItemBinding momentListViewItemBinding) {
            super(momentListViewItemBinding.getRoot());
            this.momentListViewItemBinding = momentListViewItemBinding;
        }

        public MomentItemViewHolder(View view){
            super(view);
        }
    }
}
